package com.sl.au.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.Option;
import com.sl.au.entity.BusinesssellerBaseInfo;
import com.sl.au.entity.BussinessCheck;
import com.sl.au.entity.BusinessCheckDetail;
import com.sl.au.entity.BussinessInspection;
import com.sl.au.service.BusinesssellerBaseInfoService;
import com.sl.au.service.BussinessCheckService;
import com.sl.au.service.BussinessInspectionService;
import com.sl.au.service.OptionService;
import com.sl.utils.MsgHelper;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 商户审核
 * 
 * @author Heguangchuan
 *
 */
@RestController
@RequestMapping(value = "/ui/bussinessCheck")
public class BussinessCheckController extends BaseController {

	@Autowired
	private BussinessCheckService bussinessCheckService;
	@Autowired
	private BussinessInspectionService bussinessInspectionService;
	@Autowired
	private BusinesssellerBaseInfoService businesssellerBaseInfoService;
    @Autowired
    private OptionService optionService;
    
	@RequestMapping(value = "/listAllSellers", method = RequestMethod.GET)
	@ResponseBody
	public MsgHelper listAllSeller() {
		List<BusinesssellerBaseInfo> infos = businesssellerBaseInfoService.findAll();
		return MsgHelper.success().put("sellers", infos);
	}

	@RequestMapping("/findById/{id}")
	@ResponseBody
	public MsgHelper findById(@PathVariable("id") String id) {
		BussinessCheck info = bussinessCheckService.findById(id);
		return MsgHelper.success().put("info", info);
	}
	
	@RequestMapping(value="/getProgramType",method = RequestMethod.GET)
	public Map<String, Object> getProgramType() {
		
		Map<String, Object> map=new HashMap<String, Object>();
		int code=-1;
	 List<Option> btypeforzx=this.optionService.getRepository().findByGroup("签订率");
	 List<Option> btypeforws=this.optionService.getRepository().findByGroup("环境卫生");
	 List<Option> btypeforsr=this.optionService.getRepository().findByGroup("市容秩序");
	 List<Option> btypeforwslh=this.optionService.getRepository().findByGroup("绿化美化");
	 map.put("btypeforzx", btypeforzx);
	 map.put("btypeforws", btypeforws);
	 map.put("btypeforsr", btypeforsr);
	 map.put("btypeforwslh", btypeforwslh);
	 code=1;
	 map.put("code", 1);
	 return map;
	 
	}

	@RequestMapping("/pageOnPhone")
	@ResponseBody
	public MsgHelper getPageInfoOnPhone() {
		String device = request.getParameter("device");
		String identify = request.getParameter("identify");
		if (!this.DEVICE.equals(device) && !StringUtils.hasText(device)) {
		}
		List<BussinessCheck> pageInfo = bussinessCheckService.getChecks(0, 10, identify, null, null);
		return MsgHelper.success().put("pageInfo", pageInfo);
	}
	@RequestMapping("/pageByTimeOnPhone")
	@ResponseBody
	public MsgHelper pageByTimeOnPhone() {
		String device = request.getParameter("device");
		String identify = request.getParameter("identify");
		if (!this.DEVICE.equals(device) && !StringUtils.hasText(device)) {
		}
		List<BussinessInspection> pageInfo = bussinessCheckService.getChecksByTime(0, 30, identify, null, null);
		/*List<BussinessInspection> pageHistoryInfo = bussinessCheckService.getChecksByHistory(0, 30, identify, null, null);*/
		List<BussinessCheck> pageHistoryInfo=this.bussinessCheckService.getCheckHistory(0, 30, identify, this.getMyAccount().getUser(), "checkDate");
		MsgHelper helper= MsgHelper.success().put("pageInfo", pageInfo);
		helper.put("pageHistoryInfo", pageHistoryInfo);
		return helper;
	}
	
	@RequestMapping("/checkDetailInfo")
	@ResponseBody
	public MsgHelper checkDetailInfo() {
		String device = request.getParameter("device");
		String identify = request.getParameter("identify");
		if (!this.DEVICE.equals(device) && !StringUtils.hasText(device)) {
		}
		BussinessCheck bussinessCheck =this.bussinessCheckService.getRepository().findOne(identify);
		List<BussinessInspection> recordInfo = bussinessCheckService.getInspectionByCheckId(0, 30, identify, "inspectDate");
		List<BusinessCheckDetail> detailInfo =this.bussinessCheckService.getCheckDetailByCheckId(0, 30, identify,"createTime");
		MsgHelper helper= MsgHelper.success().put("recordInfo", recordInfo);
		helper.put("detailInfo", detailInfo);
		helper.put("bussinessCheck", bussinessCheck);
		
		return helper;
	}
	
	@RequestMapping("/pageByHistoryOnPhone")
	@ResponseBody
	public MsgHelper pageByHistoryOnPhone() {
		String device = request.getParameter("device");
		String identify = request.getParameter("identify");
		if (!this.DEVICE.equals(device) && !StringUtils.hasText(device)) {
		}
		List<BussinessInspection> pageInfo = bussinessCheckService.getChecksByHistory(0, 30, identify, null, null);
		return MsgHelper.success().put("pageInfo", pageInfo);
	}
	
	/**
	 * 删除
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
	@ResponseBody
	public MsgHelper delete(@PathVariable(value = "id") String id) {
		bussinessCheckService.deleteById(id);
		return MsgHelper.success();
	}

	/**
	 * 保存巡检信息
	 * 
	 * @param bussinessInspection
	 *            表单提交过来的数据
	 * @return 构建的json数据
	 */
	@RequestMapping(value = "/saveOrUpdate", method = RequestMethod.POST)
	@ResponseBody
	public MsgHelper save(BussinessCheck bussinessCheck,
			@RequestParam(value = "bussinessId", required = true) String bussinessId) {
		// 关联非表单数据
		BusinesssellerBaseInfo info = businesssellerBaseInfoService.findByBussinessSellerId(bussinessId);
		bussinessCheck.setBusinesssellerBaseInfo(info);
		bussinessCheck.setCheckDate(new Date());
		bussinessCheck.setUser(getMyAccount().getUser());
		bussinessCheckService.save(bussinessCheck);
		return MsgHelper.success();
	}
	
	@RequestMapping(value = "/saveCheckAndDetailWithFile", method = RequestMethod.POST)
	public Map<String,Object> saveCheckAndDetailWithFile(
			MultipartHttpServletRequest requests) {
		 MultipartFile file = requests.getFile("file");
		 
		Map<String,Object> map =new HashMap<String,Object>();
		int code=-1;
		// 关联非表单数据
		BusinesssellerBaseInfo info = businesssellerBaseInfoService.findByBussinessSellerId(request.getParameter("bussinessId"));
		
		// 获取当前Check图片的存储路径
		    String url="";
				if (file != null&&!file.isEmpty()) {
					// 注意路径的构建
				 url = getUploadFilePath(this.fileUploadPath, "img/check", file);
				}
		
		JSONObject project = JSONObject.fromObject(request.getParameter("bussinessCheck"));
		BussinessCheck bussinessCheck = (BussinessCheck) JSONObject.toBean(project,
				BussinessCheck.class);
		bussinessCheck.setBusinesssellerBaseInfo(info);
		bussinessCheck.setCheckDate(new Date());
		bussinessCheck.setUser(getMyAccount().getUser());
		bussinessCheck.setPictureAddr(url);
		
		List<BusinessCheckDetail> dlist=new ArrayList<>();
		
		JSONArray businessCheckDetailList = JSONArray.fromObject(request.getParameter("businessCheckDetail"));
				for (int i = 0; i < businessCheckDetailList.size(); i++) {
				JSONObject jsonObject = businessCheckDetailList.getJSONObject(i);
				BusinessCheckDetail businessCheckDetail = (BusinessCheckDetail) JSONObject.toBean(jsonObject,
						BusinessCheckDetail.class);
				businessCheckDetail.setCreateTime(new Date());
				businessCheckDetail.setBussinessCheck(bussinessCheck);
				file =requests.getFile(businessCheckDetail.getCheckTypeInfo().getId());
				
				if (file != null&&!file.isEmpty()) {
					// 注意路径的构建
				 url = getUploadFilePath(this.fileUploadPath, "img/checkDetail", file);
				 businessCheckDetail.setPictureAdress(url);
				}
				
				dlist.add(businessCheckDetail);
				}
				
		List<BussinessInspection> list=this.bussinessInspectionService.findByIds(request.getParameter("inspectionIdList"));
				
		for(BussinessInspection b:list)
		{
			b.setCheck(bussinessCheck);
		}
		bussinessCheckService.saveAll(bussinessCheck, dlist, list);
		code=1;
		map.put("code", code);
		return map;
	}
	
	@RequestMapping(value = "/saveCheckAndDetail", method = RequestMethod.POST)
	public MsgHelper saveCheckAndDetail(@RequestBody Map<String, Object> map) {
		// 关联非表单数据
		BusinesssellerBaseInfo info = businesssellerBaseInfoService.findByBussinessSellerId((String)map.get("bussinessId"));
		
		//BussinessCheck bussinessCheck =new BussinessCheck();
		/*JSONArray jlist = JSONArray.fromObject(map.get("bussinessCheck"));*/
		/*Iterator<Object> it = jlist.iterator();
		while (it.hasNext()) {
		    JSONObject ob = (JSONObject) it.next();
		    bussinessCheck.setCheckCondition(ob.getString("checkCondition"));
		    bussinessCheck.setLatitude(ob.getDouble("latitude"));
		    bussinessCheck.setLongitude(ob.getDouble("longitude"));
		    bussinessCheck.setRectifyCondition(ob.getString("rectifyCondition"));
		    bussinessCheck.setRemark(ob.getString("remark"));
		    bussinessCheck.setPictureAddr(ob.getString("pictureAddr"));
		}*/
		
		JSONObject project = JSONObject.fromObject(map.get("bussinessCheck"));
		BussinessCheck bussinessCheck = (BussinessCheck) JSONObject.toBean(project,
				BussinessCheck.class);
		bussinessCheck.setBusinesssellerBaseInfo(info);
		bussinessCheck.setCheckDate(new Date());
		bussinessCheck.setUser(getMyAccount().getUser());
		List<BusinessCheckDetail> dlist=new ArrayList<>();
		
		JSONArray businessCheckDetailList = JSONArray.fromObject(map.get("businessCheckDetail"));
				for (int i = 0; i < businessCheckDetailList.size(); i++) {
				JSONObject jsonObject = businessCheckDetailList.getJSONObject(i);
				BusinessCheckDetail businessCheckDetail = (BusinessCheckDetail) JSONObject.toBean(jsonObject,
						BusinessCheckDetail.class);
				businessCheckDetail.setCreateTime(new Date());
				businessCheckDetail.setBussinessCheck(bussinessCheck);
				dlist.add(businessCheckDetail);
				}
		
		
		//BusinessCheckDetail businessCheckDetail=(BusinessCheckDetail)map.get("businessCheckDetail");
		List<BussinessInspection> list=this.bussinessInspectionService.findByIds((String)map.get("inspectionIdList"));
				
		for(BussinessInspection b:list)
		{
			b.setCheck(bussinessCheck);
		}
		bussinessCheckService.saveAll(bussinessCheck, dlist, list);
		return MsgHelper.success();
	}

	/**
	 * 
	 * @param map
	 *            存放到页面的数据
	 * @return
	 */
	@RequestMapping(value = "/saveOrUpdate", method = RequestMethod.GET)
	public ModelAndView saveUI(Map<String, Object> map) {

		map.put("id", "");

		String device = request.getParameter("device");
		String identify = request.getParameter("identify");
		String inspectionIdList=request.getParameter("inspectionIdList");
		
		if (this.DEVICE.equals(device) && StringUtils.hasText(device)) {
			ModelAndView modelAndView = new ModelAndView();
			modelAndView.setViewName("mobile/bussinessCheck/saveOrUpdateOnPhone");
			modelAndView.addObject("bussinessId", identify);
			modelAndView.addObject("inspectionIdList",inspectionIdList);
			return modelAndView;
		} else {
			return createLayoutView("bussinessCheck/saveOrUpdate");
		}
	}

	/**
	 * 
	 * @param id
	 *            到修改页面传的id
	 * @param map
	 *            存放到页面所需要的数据
	 * @return
	 */
	@RequestMapping(value = "/saveOrUpdate/{id}", method = RequestMethod.GET)
	public ModelAndView updateUI(@PathVariable("id") String id, Map<String, Object> map) {
		map.put("id", id);

		String device = request.getParameter("device");
		String identify = request.getParameter("identify");
		if (this.DEVICE.equals(device) && StringUtils.hasText(device)) {
			ModelAndView modelAndView = new ModelAndView();
			modelAndView.setViewName("mobile/bussinessCheck/saveOrUpdateOnPhone");
			modelAndView.addObject("bussinessId", identify);
			return modelAndView;
		} else {
			return createLayoutView("bussinessCheck/saveOrUpdate");
		}
	}

	/**
	 * 初始化分页数据
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/page", method = RequestMethod.GET)
	public Map<String, Object> getPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		List<BussinessCheck> checks = null;
		int count = 0;
		String device = request.getParameter("device");
		String url = request.getParameter("url");
		String identify = request.getParameter("identify");
		if (StringUtils.hasText(device) && this.DEVICE.equals(device)) {
			checks = bussinessCheckService.getChecks(start, length, identify, null, null);
		} else {
			if (StringUtils.hasText(key)) {
				checks = bussinessCheckService.getChecks(start, length, key, null, null);
			} else {
				checks = bussinessCheckService.getPage(start, length, null, null, null);
			}
		}
		count = bussinessCheckService.getCount(key);
		map.put("data", checks);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	/**
	 * 初始化页面
	 * 
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index(ModelAndView modelAndView) {

		String device = request.getParameter("device");
		String url = request.getParameter("url");
		String identify = request.getParameter("identify");
		// 移动端
		if (StringUtils.hasText(device) && this.DEVICE.equals(device)) {
			// 移动端访问的首页
			modelAndView.setViewName("mobile/bussinessCheck/indexOnPhone");
			modelAndView.addObject("bussinessId", identify);
			modelAndView.addObject("device", device);
			modelAndView.addObject("url", url);
		} else {
			// PC端
			modelAndView = createLayoutView("bussinessCheck/bussinessCheck");
		}
		return modelAndView;
	}

}
